<?php
// +----------------------------------------------------------------------
// | ebSIG
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.ebsig.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: liudaojian <liudaojian@ebsig.com>
// +----------------------------------------------------------------------

/**
 * 临沂孚惠项目 - CRM接口类
 * @author   liudaojian <liudaojian@ebsig.com>
 * @version 1.0
 */

namespace App\Service\Rpc\Crm;

use Carbon\Carbon;

use App\Service\HttpService;

use App\Models\Mall\MallMaster; //门店主表

use App\Models\Log\LogEaiCrm; //crm接口日志表

use App\Models\Customer\Customer; //会员主表

use App\Models\ConfigureFunction; //功能配置表

use Illuminate\Support\Facades\Redis as Redis;


/**
 *      @方法  	requestApi			请求接口
 *      @方法  	customerQuery		查询会员信息
 *      @方法  	customerEdit		修改会员信息
 *      @方法  	openCard			开卡
 *      @方法  	bindCard			绑卡
 *      @方法  	pointsQuery			获取总积分
 *      @方法  	pointsAdd			通过卡号增加积分
 *      @方法  	pointsReduction		通过卡号减少积分
 *      @方法  	pointsLogs			积分变更流水
 *      @方法  	accountQuery		卡余额查询
 *      @方法  	consumption			卡余额消费(支付)
 *      @方法  	recharge			卡余额充值
 *      @方法  	accountLogs			卡消费流水(余额变更记录)
 */

class LyfhCrm
{

    private $org_code = 'W9625'; //组织代码

    private $cardId = '9625'; //项目标识

    //用户会员名
    private $custID = 0;

    //会员号
    private $card_no = 0;

    public function requestApi($request_url, $api_name, $get_data = [], $post_data = [], $request_way = 'get' )
    {

        $start_time = microtime( true );

        //实例http类
        $ebsigHttp = new HttpService();

        //连接接口参数
        $http_opts = [
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            CURLOPT_USERPWD => 'guest:guest',
            CURLOPT_HTTPHEADER => array('Accept: application/json', 'Content-Type: application/json')
        ];

        //请求接口
        if ( $request_way == 'get' ) {

            if( !empty( $get_data ) ){
                $get_data_str = http_build_query( $get_data );
                $result_array = $ebsigHttp->get($request_url . '?' . $get_data_str,$http_opts);
            } else {
                $result_array = $ebsigHttp->get( $request_url ,$http_opts);
            }

        } else if ( $request_way == 'post:json' ) {

            if ( !empty( $get_data ) ) {
                $request_url .= '?' . http_build_query($get_data);
            }

            $post_data_json = json_encode($post_data);

            $result_array = $ebsigHttp->post( $request_url, $post_data_json ,$http_opts);

        } else if ( $request_way == 'put:json' ) {

            if ( !empty( $get_data ) ) {
                $request_url .= '?' . http_build_query( $get_data );
            }

            $post_data_json = json_encode( $post_data);

            $result_array = $ebsigHttp->put( $request_url, $post_data_json ,$http_opts);

        } else {

            $post_data_json = json_encode( $post_data );

            $result_array = $ebsigHttp->post( $request_url, $post_data_json ,$http_opts);

        }

        $return_code = 200;

        $end_time = microtime(true);

        if ( isset( $result_array['errCode']) && $result_array['errCode'] != 0 ) {
            $return_code = $result_array['errCode'];
            $return_array = [
                'code' => 404,
                'message' => $result_array['message']
            ];
        }else if ( isset( $result_array['errorCode']) && $result_array['errorCode'] != 0 ) {
            $return_code = $result_array['errorCode'];
            $return_array = [
                'code' => 400,
                'message' => $result_array['message']
            ];
        } else {
            $return_array = [
                'code' => 200,
                'message' => 'ok',
                'data' => isset( $result_array) ? $result_array : 'null'
            ];

        }

        //会员信息
        $custID = 0;
        $card_no = 0;
        $cust_array = [];

        if ( $custID ) {

            $cust_array = Customer::select('pcustID','custID')->where(['custID'=>$custID])->first();
        }

        if ( empty( $cust_array ) && $card_no ) {

            $cust_array = Customer::select('pcustID','custID')->where(['card_no'=>$card_no])->first();
        }

        //保存接口日志信息
        $log_interface = new LogEaiCrm();
        $log_interface->creator = 'LYFH';
        $log_interface->uuid = makeUuid();
        $log_interface->timeStamp = Carbon::now();
        $log_interface->createTime = Carbon::now();
        $log_interface->api_name = $api_name;
        $log_interface->pcustID = isset( $cust_array['pcustID'] ) ? $cust_array['pcustID'] : 0;
        $log_interface->custID = isset( $cust_array['custID'] ) ? $cust_array['custID'] : 0;
        $log_interface->request_status = $return_code == 200 ? 2 : 3;
        if( !empty( $get_data ) || !empty( $post_data ) ) {
            $log_interface->request_data = print_r( array_merge( $get_data, $post_data ), true );
        }
        $log_interface->return_data = print_r( $result_array, true );
        $log_interface->return_code = $return_code;
        $log_interface->return_msg  = $return_array['message'];
        $log_interface->exec_time = ( $end_time - $start_time ) * 1000;
        $log_interface->save( );

        return $return_array;

    }


    /**
     * 获取选店信息并同步门店
     * @param $arg_array
     * @return array
     */
    public function adjustOrgCode( $arg_array )
    {

        //获取选店信息
        if ( isset( $args_array['session_id']) && !empty( $args_array['session_id'] ) ) {
            //获取选店信息
            $select_mall = redisTransformation( Redis::get($args_array['session_id'] . 'CUST_SELECTMALL'));
            if( !empty($select_mall) ){
                $this->org_code = $select_mall['mallCode'];
            }
        }

        //若有传入门店号，则替换传入的门店
        if ( isset( $arg_array['mallCode'] ) && !empty( $arg_array['mallCode'] ) ) {
            $this->org_code = $arg_array['mallCode'];
        }

        //如果组织代码仍为空，则采用默认组织代码—虚拟门店代码
        if ( empty( $this->org_code ) ) {
            $this->org_code = 'W9625';
        }
    }


    /**
     * 根据手机号查询会员资料
     * @param array  $args_array                     参数数组
     *        string  $args_array['mobilenum']        手机号              必须
     *
     * @return array('code'=>'','message'=>'','data'=>'')
     */
    public function customerQuery( $args_array )
    {

        //手机号
        if ( !isset( $args_array['mobilenum'] ) || empty( $args_array['mobilenum'] ) ) {
            return ['code'=>400,'message'=>'手机号不能为空'];
        }

        $this->custID = $args_array['mobilenum'];

        //标示性传入参数
        $request_params['operCtx'] = [
            'time' => '',
            'operator' => [
                'namespace'=>'WDH',
                'id'=>'10000',
                'fullName'=>'WDH[10000]',
            ],
            'terminalId'=>'wx',
            'store'=>$this->org_code,
        ];

        //传入请求参数
        $request_params['accout'] = [
            'type' => 'mobile',
            'id' => $args_array['mobilenum']
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/account/check';

        //调用接口
        $request_res = $this->requestApi( $request_url, 'customerQuery', array(), $request_params, 'post' );

        //调用接口
        if ( $request_res['code'] != 200 || $request_res['data']['errorCode'] != 0 ) {
            return ['code'=>404,'message'=>'没有找到会员数据'];
        }

        if ( $request_res['data']['response']['cardInfo']['state'] !='使用中' ) {
            return ['code'=>404,'message'=>'会员卡号异常'];
        }

        $return_data = [
            'offline_pcustID' => $request_res['data']['response']['cardInfo']['cardNum'],
            'cardNo' => $request_res['data']['response']['cardInfo']['cardNum'],
            'mobile' => $request_res['data']['response']['member']['cellphone'],
            'custname' => $request_res['data']['response']['member']['name']
        ];


        return ['code' => 200,'message' =>'ok','data'=>$return_data ];

    }


    /**
     * 会员基本信息修改
     *  @param	array	$args_array		请求参数
     *      string		$args_array['custname']	姓名		可选
     *      string		$args_array['sexy']	    性别		0.未知  1.男  2.女 可选
     *      string		$args_array['birthday']	生日		如“1990-09-10”可选
     * 		string		$args_array['mobile']	手机号		可选
     *      string		$args_array['email']	邮箱		可选
     *      string		$args_array['QQ']	    QQ		    可选
     *      string		$args_array['address']	地址		可选
     * 		string		$args_array['identityCard']	身份证  可选
     * @return array
     */
    public function customerEdit( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return ['code'=>400,'message'=>'卡号不能为空'];
        }
        $this->card_no = $args_array['cardNo'];

        //会员姓名
        if ( isset( $args_array['custname'] ) && !empty( $args_array['custname'] ) ) {
            $name = $args_array['custname'];
        } else {
            $name = $args_array['mobile'];
        }

        //性别
        if ( isset( $args_array['sexy']) && $args_array['sexy'] == 1 ) {
            $gender = 'male';
        } else if ( $args_array['sexy'] && $args_array['sexy'] == 2 ) {
            $gender = 'female';
        } else {
            $gender = 'unknown';
        }

        //会员生日
        if( isset( $args_array['birthday'] ) && !empty( $args_array['birthday'] ) ) {
            $birthdays = explode('-',$args_array['birthday']);
            $birthday = [
                'year'=>$birthdays[0],
                'month'=>$birthdays[1],
                'day'=>$birthdays[2]
            ];
        } else {
            $birthday = [
                'year'=>'1985',
                'month'=>'01',
                'day'=>'01'
            ];
        }

        //会员手机号
        if( isset( $args_array['mobile'] ) && !empty( $args_array['mobile'] ) ) {
            $cellphone = $args_array['mobile'];
        } else {
            $cellphone = '';
        }
        $this->custID = $args_array['mobile'];

        //会员邮箱
        if( isset( $args_array['email'] ) && !empty( $args_array['email'] ) ) {
            $email = $args_array['email'];
        } else {
            $email = '';
        }

        //会员QQ
        if( isset( $args_array['QQ'] ) && !empty( $args_array['QQ'] ) ) {
            $qq = $args_array['QQ'];
        } else {
            $qq = '';
        }

        //会员地址
        if( isset( $args_array['address'] ) && !empty( $args_array['address'] ) ) {
            $address = $args_array['address'];
        } else {
            $address = '';
        }

        //会员身份证
        if( isset( $args_array['identityCard'] ) && !empty( $args_array['identityCard'] ) ) {
            $idCard = [
                'type'=>'idCard',
                'id'=>$args_array['identityCard']
            ];
        } else {
            $idCard = [
                'type'=>'idCard',
                'id'=>''
            ];
        }

        //调整组织代码
        $this->adjustOrgCode( $args_array );

        //标示性传入参数
        $request_params['operCtx'] = [
            'time'=>'',
            'operator'=>[
                'namespace'=>'WDH',
                'id'=>'10000',
                'fullName'=>'WDH[10000]',
            ],
            'terminalId'=>'wx',
            'store'=>$this->org_code,
        ];

        $mumber_carrier = $this->queryByCardNo( $args_array );

        if ( $mumber_carrier['code'] != 200 ) {
            return ['code'=>400,'message'=>$mumber_carrier['message']];
        }

        //传入请求参数
        $request_params['member'] = [
            'id' =>$mumber_carrier['data']['id'],
            'name' =>$name,
            'gender' => $gender,
            'birthday'=>$birthday,
            'email'=>$email,
            'idCard'=>$idCard,
            'cellphone'=>$cellphone,
            'address'=>$address,
            'qq'=>$qq
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/mbr/saveModify';

        //调用接口
        $request_res = $this->requestApi( $request_url, 'updateUserInfo', array() , $request_params , 'post' );

        //返回状态错误码 0.成功
        if ( $request_res['code'] == 200 && $request_res['data']['errorCode'] != 0 ) { //0 成功

            return ['code' => 404, 'message' => $request_res['data']['message']];
        }

        return ['code' => $request_res['code'], 'message' => $request_res['message']];

    }


    /**
     * 通过卡号查询会员
     * @param	array	$args_array		请求参数
     * 	      string		$args_array['cardNo']	卡号	必选
     *
     * @return array
     */
    public function queryByCardNo( $args_array ){

        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return ['code'=>400,'message'=>'卡号不能为空'];
        }
        $this->card_no = $args_array['cardNo'];

        //调整组织代码
        $this->adjustOrgCode($args_array);

        //标示性传入参数
        $result_array['operCtx'] = [
            'time'=>'',
            'operator'=>[
                'namespace'=>'WDH',
                'id'=>'10000',
                'fullName'=>'WDH[10000]',
            ],
            'terminalId'=>'wx',
            'store'=>$this->org_code,
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/card/'.$args_array['cardNo'];

        //调用接口
        $request_res = $this->requestApi( $request_url, 'queryByCardNo', array() , $result_array , 'get' );

        if ( $request_res['code'] != 200 || empty( $request_res['data'] ) ) {
            return ['code' => $request_res['code'], 'message' => $request_res['message']];
        }

        //返回状态错误码 0.成功
        if ( $request_res['code']['errorCode'] != 0 ) { //0 成功
            return ['code' => 404, 'message' => $request_res['data']['message']];
        }

        return [
            'code' => $request_res['code'],
            'message' => $request_res['message'],
            'data' => [
                'id'=>$request_res['data']['card']['carrier']
            ]
        ];

    }


    /**
     *
     * 会员开卡
     * @param	array
     * 	$args_array		请求参数
     * 		string		$args_array['mobile']	手机号		必选
     * 		string		$args_array['openId']	微信openid	可选
     * 		string		$args_array['custID']	会员号		可选
     *      string		$args_array['custname']	姓名		可选
     *      string		$args_array['sexy']	    性别		0.未知  1.男  2.女 可选
     *      string		$args_array['birthday']	生日		如“1990-09-10”可选
     *      string		$args_array['idCard']	= array(
     *                                  'id'=>'string',
     *                                  'type' =>'string'
     * )                            证件      必选
     * @return array
     */
    public function openCard( $args_array )
    {

        //手机号
        if ( !isset( $args_array['mobile'] ) || empty( $args_array['mobile'] ) ) {
            return [ 'code'=>400 , 'message'=>'手机号不能为空'];
        }
        $this->custID = $args_array['mobile'];
        $openId = $args_array['mobile'];

        //openId 存在
        if ( isset( $args_array['openId'] ) && !empty( $args_array['openId'] ) ) {
            $openId = $args_array['openId'];
        }

        //设置请求参数
        $business_params = [
            'openId' => $openId,
            'cardId' => $this->cardId  //项目标识
        ];

        //姓名
        if ( isset( $args_array['custname'] ) && !empty( $args_array['custname'] ) ) {
            $member_params['name'] = $args_array['custname'];
        }

        //会员id
        if ( isset( $args_array['custID'] ) && !empty( $args_array['custID'] ) ) {
            $member_params['id'] = $args_array['custID'];
            $this->custID = $args_array['custID'];
        }

        //手机号
        if ( !empty( $args_array['mobile'] ) ) {
            $member_params['cellphone'] = $args_array['mobile'];
        }

        //性别
        if ( isset( $args_array['sexy']) && $args_array['sexy'] == 1 ) {
            $member_params['gender'] = 'male';
        } else if ( isset( $args_array['sexy'] ) && $args_array['sexy'] == 2 ) {
            $member_params['gender'] = 'female';
        } else {
            $member_params['gender'] = 'unknown';
        }

        //生日
        if ( isset( $args_array['birthday'] ) && !empty( $args_array['birthday'] ) ) {
            $birthdays = explode('-',$args_array['birthday']);
            $birthday = [
                'year'=>$birthdays[0],
                'month'=>$birthdays[1],
                'day'=>$birthdays[2]
            ];
            $member_params['birthday'] = $birthday;
        }

        //证件
        if( isset( $args_array['identityCard'] ) && !empty( $args_array['identityCard'] ) ) {
            $member_params['idCard'] = [
                'id' => $args_array['identityCard'],
                "type"=> "idCard"
            ];
        }

        //调整组织代码
        $this->adjustOrgCode( $args_array );

        //标示性传入参数
        $request_params['operCtx'] = [
            'time' => '',
            'operator' => [
                'namespace'=>'WDH',
                'id'=>'10000',
                'fullName'=>'WDH[10000]',
            ],
            'terminalId'=>'wx',
            'store'=>$this->org_code,
        ];

        //传入请求参数
        $request_params['request'] = [
            'extMember' => $business_params,
            'member' => $member_params
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/card/openCard';

        //调用接口
        $request_res = $this->requestApi( $request_url, 'openCard', array(), $request_params, 'post' );

        if ( $request_res['code'] != 200 || empty( $request_res['data'] ) ) {
            return ['code' => $request_res['code'], 'message' => $request_res['message']];
        }

        //返回状态错误码 0.成功
        if ( $request_res['data']['errorCode'] != 0 ) { //0 成功
            return ['code' => 404, 'message' => $request_res['data']['message']];
        }

        $periodOfValidity = '';
        if ( !empty( $request_res['data']['card']['bytime'] ) ) {
            $periodOfValidity = date('Y-m-d H:i:s', strtotime( $request_res['data']['card']['bytime'] ) );
        }

        return [
            'code' => $request_res['code'],
            'message' => $request_res['message'],
            'data' => [
                'cardNo' => $request_res['data']['card']['cardNum'],
                'periodOfValidity' => $periodOfValidity,
                'offline_pcustID' => $request_res['data']['card']['carrier']
            ]
        ];

    }


    /**
     * 查询会员账户积分信息
     * @param array $args_array
     *      string	    $args_array['cardNo']   卡号        必选
     *
     * @return array
     */
    public function pointsQuery( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return ['code'=>400,'message'=>'卡号不能为空'];
        }
        $this->card_no = $args_array['cardNo'];

        //调整组织代码
        $this->adjustOrgCode( $args_array );

        //标识性传入参数
        $request_params['operCtx'] = [
            'time'=>date("Y-m-d\TH:i:s").'.000+0800',
            'operator'=>[
                'namespace'=>'WDH',
                'id'=>'10000',
                'fullName'=>'WDH[10000]',
            ],
            'terminalId'=>'wx',
            'store'=>$this->org_code,
        ];

        $request_params['accout'] = [
            'type' => 'cardNum',
            'id' => $args_array['cardNo']
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/account/check';

        //调用接口
        $request_res = $this->requestApi( $request_url, 'pointsQuery', array(), $request_params, 'post:json' );
        if ( $request_res['code'] != 200 ) {
            return ['code'=>$request_res['code'],'message'=>$request_res['message']];
        }

        $points = 0;
        if( isset( $request_res['data']['response'] ) && isset( $request_res['data']['response']['scoreAccount']['score'] ) ) {
            $points = $request_res['data']['response']['scoreAccount']['score'];
        }

        return ['code' => 200, 'message' => 'ok','data'=>['points'=>$points]];
    }


    /**
     * 会员账户积分增加
     * @param array $args_array
     * @return array
     */
    public function pointsAdd( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return ['code'=>400 , 'message'=>'卡号不能为空'];
        }
        $this->card_no = $args_array['cardNo'];

        //增加积分
        if ( !isset( $args_array['points'] ) || empty( $args_array['points'] ) ) {
            return ['code'=>400 , 'message'=>'积分值不能为空'];
        }

        if ( !isset( $args_array['tranId'] ) || empty( $args_array['tranId'] ) ) {
            $args_array['tranId'] = makeUuid();
        }

        //备注
        if ( !isset( $args_array['remark'] ) || empty( $args_array['remark'] ) ) {
            $args_array['remark'] = null;
        }

        //调整组织代码
        $this->adjustOrgCode( $args_array );

        //标识性传入参数
        $request_params['operCtx'] = [
            'time'=>date("Y-m-d\TH:i:s").'.000+0800',
            'operator'=>[
                'namespace'=>'WDH',
                'id'=>'10000',
                'fullName'=>'WDH[10000]',
            ],
            'terminalId'=>'wx',
            'store'=>$this->org_code,
        ];

        //设置请求参数
        $request_params['request'] = [
            'tranId' => $args_array['tranId'],
            'xid' => time(),
            'tranTime' => date("Y-m-d\TH:i:s").'.000+0800',
            'account' =>[
                'type' => 'cardNum',
                'id' => $args_array['cardNo'],
            ],
            'scoreRec' => [
                'scoreType' => '-',
                'scoreSubject' => '调整',
                'score' => $args_array['points'],
            ],
            'remark' => '微电汇'.$args_array['remark'],
            'action' => '消费'

        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/score/adjustScore';

        //调用接口
        return $request_res = $this->requestApi( $request_url, 'pointsQuery', array(), $request_params, 'post:json' );

    }


    /**
     * 会员账户积分扣减
     * @param array $args_array
     * @return array
     */
    public function pointsReduction( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return ['code'=>400 , 'message'=>'卡号不能为空'];
        }
        $this->card_no = $args_array['cardNo'];

        //扣减积分
        if ( !isset( $args_array['points'] ) || empty( $args_array['points'] ) ) {
            return ['code'=>400 , 'message'=>'积分值不能为空'];
        }

        //获取来源
        if ( !isset( $args_array['scoreSource'] ) || empty( $args_array['scoreSource'] ) ) {
            $args_array['scoreSource'] = '';
        }

        if ( !isset($args_array['tranId'] ) || empty( $args_array['tranId'] ) ) {
            $args_array['tranId'] = makeUuid();
        }

        //备注
        if ( !isset( $args_array['remark'] ) || empty( $args_array['remark'] ) ) {
            $args_array['remark'] = null;
        }

        //调整组织代码
        $this->adjustOrgCode( $args_array );

        //标识性传入参数
        $request_params['operCtx'] = [
            'time'=>date("Y-m-d\TH:i:s").'.000+0800',
            'operator'=>[
                'namespace'=>'WDH',
                'id'=>'10000',
                'fullName'=>'WDH[10000]',
            ],
            'terminalId'=>'wx',
            'store'=>$this->org_code,
        ];

        //设置请求参数
        $request_params['request'] = [
            'tranId' => $args_array['tranId'],
            'xid' => time(),
            'tranTime' => date("Y-m-d\TH:i:s").'.000+0800',
            'account' =>[
                'type' => 'cardNum',
                'id' => $args_array['cardNo']
            ],
            'scoreRec' => [
                'scoreType' => '-',
                'scoreSubject' => '消费',
                'score' => '-'.$args_array['points']
            ],
            'remark' => '微电汇'.$args_array['remark'],
            'action' => '消费'
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/score/adjustScore';

        //调用接口
        return $request_res = $this->requestApi( $request_url, 'pointsReduction', array(), $request_params, 'post:json' );

    }


    /**
     * 会员账户积分变更记录
     * @param array $args_array
     * @return array
     */
    public function pointsLogs( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return ['code'=>400 , 'message'=>'卡号不能为空'];
        }
        $this->card_no = $args_array['cardNo'];

        //调整组织代码
        $this->adjustOrgCode( $args_array );

        //传入请求参数
        $request_params = [
            "conditions" => [
                [
                    "operation" => "cardNumEquals",
                    "parameters" => [
                        $args_array['cardNo']
                    ]
                ]
            ],
            "orders" => [
                [
                    "field" => "tranTime",
                    "direction" => "desc"
                ]
            ],
            "pageSize" =>!empty( $args_array['rp'] ) ? $args_array['rp'] : 10,
            "page" => !empty( $args_array['page'] ) ? intval( $args_array['page'])-1 : 0,
            "probePages" => 0
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/score/queryScoreHst';

        //调用接口
        $request_res = $this->requestApi( $request_url, 'pointsLogs', array(), $request_params, 'post' );

        if ( $request_res['code'] != 200 ) {
            return ['code'=>$request_res['code'],'message'=>$request_res['message']];
        }

        //页码
        $pointsLogs_data = [
            'page'  => intval( $request_res['data']['paging']['page'] )+1,
            'pageSize'  => $request_res['data']['paging']['pageSize'],
            'pageCount'=>$request_res['data']['paging']['pageCount'],
            'count' => !empty( $request_res['data']['paging']['recordCount'] ) ? $request_res['data']['paging']['recordCount'] : 0,
        ];

        foreach ( $request_res['data']['records'] as $key=>$value ) {

            $pointsLogs_data['data'][] = [
                'createTime'  => date('Y-m-d H:i:s',strtotime($value['tranTime'])), //时间
                'changeAccount' => abs( $value['occurScore'] ), //增加或减少的积分
                'code' => $value['num'], //消费代码
                'remark' =>$value['remark'], //消费名称
                'storeName' => $value['store'], //店名称
                'storeCode' => $value['store'], //店号
                'oldScore' => $value['oldScore'], //原始积分
                'changeType' => $value['occurScore'] > 0 ? 1: 0 , //状态 ,1:增加积分  0: 减少积分
            ];
        }


        return ['code'=>200,'message'=>$request_res['message'],'data'=>$pointsLogs_data];

    }


    /**
     * 查询会员账户余额信息
     * @param array $args_array
     *      string	    $args_array['cardNo']   卡号        必选
     *
     * @return array
     */
    public function accountQuery( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return ['code'=>400 , 'message'=>'卡号不能为空'];
        }
        $this->card_no = $args_array['cardNo'];

        //调整组织代码
        $this->adjustOrgCode( $args_array );

        //标识性传入参数
        $request_params['operCtx'] = [
            'time'=>date("Y-m-d\TH:i:s").'.000+0800',
            'operator'=>[
                'namespace'=>'WDH',
                'id'=>'10000',
                'fullName'=>'WDH[10000]',
            ],
            'terminalId'=>'wx',
            'store'=>$this->org_code,
        ];

        //设置请求参数
        $request_params['accout'] = [
            'type' => 'cardNum',
            'id' => $args_array['cardNo']
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/account/check';

        //调用接口
        $request_res = $this->requestApi( $request_url, 'accountQuery', array(), $request_params, 'post' );
        if ( $request_res['code'] != 200 ) {
            return ['code'=>$request_res['code'],'message'=>$request_res['message']];
        }

        $balance = 0.00;
        if( isset( $request_res['data']['response'] ) && isset( $request_res['data']['response']['desAccount']['balance'] ) ) {
            $balance = $request_res['data']['response']['desAccount']['balance'];
        }


        return ['code' => 200, 'message' => 'ok','data'=>['balance'=>$balance]];

    }


    /**
     * 会员账户余额充值
     * @param array $args_array
     * @return array
     */
    public function recharge( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return ['code'=>400 , 'message'=>'卡号不能为空'];
        }
        $this->card_no = $args_array['cardNo'];

        //交易金额
        if( !isset( $args_array['amount'] ) || empty( $args_array['amount'] ) || $args_array['amount'] <= 0 ){
            return ['code'=>400 , 'message'=>'交易金额错误'];
        }

        if ( !isset( $args_array['tranId'] ) || empty( $args_array['tranId'] ) ) {
            $args_array['tranId'] = time();
        }

        //备注
        if ( !isset( $args_array['remark'] ) || empty( $args_array['remark'] ) ) {
            $args_array['remark'] = null;
        }

        //调整组织代码
        $this->adjustOrgCode( $args_array );

        //标识性传入参数
        $request_params['operCtx'] = [
            'time'=>date("Y-m-d\TH:i:s").'.000+0800',
            'operator'=>[
                'namespace'=>'WDH',
                'id'=>'10000',
                'fullName'=>'WDH[10000]',
            ],
            'terminalId'=>'wx',
            'store'=>$this->org_code,
        ];

        //设置请求参数
        $request_params['request'] = [
            'tranId' => $args_array['tranId'],
            'xid' => time(),
            'tranTime' => date("Y-m-d\TH:i:s").'.000+0800',
            'account' =>[
                'type' => 'cardNum',
                'id' => $args_array['cardNo'],
            ],
            'total' => $args_array['amount'],
            'payTotal' => $args_array['amount'],
            'tranType' => 'cash'
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/account/deposit';

        //调用接口
        return $request_res = $this->requestApi( $request_url, 'recharge', array(), $request_params, 'post:json' );

    }


    /**
     * 会员账户余额消费
     * @param array $args_array
     * @return array
     */
    public function consumption( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return ['code'=>400 , 'message'=>'卡号不能为空'];
        }
        $this->card_no = $args_array['cardNo'];

        //交易金额
        if( !isset( $args_array['amount'] ) || empty( $args_array['amount'] ) || $args_array['amount'] <= 0 ) {
            return ['code'=>400 , 'message'=>'交易金额错误'];
        }

        if ( !isset( $args_array['tranId'] ) || empty( $args_array['tranId'] ) ) {
            $args_array['tranId'] = makeUuid();
        }

        //调整组织代码
        $this->adjustOrgCode( $args_array );

        //标识性传入参数
        $request_params['operCtx'] = [
            'time'=>date("Y-m-d\TH:i:s").'.000+0800',
            'operator'=>[
                'namespace'=>'WDH',
                'id'=>'10000',
                'fullName'=>'WDH[10000]',
            ],
            'terminalId'=>'wx',
            'store'=>$this->org_code,
        ];

        //设置请求参数
        $request_params['request'] = [
            'tranId' => $args_array['tranId'],
            'xid' => time(),
            'tranTime' => date("Y-m-d\TH:i:s").'.000+0800',
            'account' =>[
                'type' => 'cardNum',
                'id' => $args_array['cardNo'],
            ],
            'total' => $args_array['amount'],
            'password' => $args_array['password'] ? $args_array['password'] : null
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/account/pay';

        //调用接口
        return $request_res = $this->requestApi( $request_url, 'consumption', array(), $request_params, 'post:json' );

    }


    /**
     * 会员账户余额变更记录
     * @param array $args_array
     * @return array
     */
    public function accountLogs( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return ['code'=>400 , 'message'=>'卡号不能为空'];
        }
        $this->card_no = $args_array['cardNo'];

        //调整组织代码
        $this->adjustOrgCode( $args_array );

        //传入请求参数
        $request_params = [
            "conditions" => [
                [
                    "operation" => "cardNumEquals",
                    "parameters" => [
                        $args_array['cardNo']
                    ]
                ]
            ],
            "orders" => [
                [
                    "field" => "tranTime",
                    "direction" => "desc"
                ]
            ],
            "pageSize" =>!empty( $args_array['rp']) ? $args_array['rp'] : 10,
            "page" => !empty( $args_array['page'] ) ? intval( $args_array['page'] )-1 : 0
        ];

        //请求地址
        $request_url = 'http://www.fuhui8888.com:10012/jcrm-server-card/rest/desHistory/query';

        //调用接口
        $request_res = $this->requestApi( $request_url, 'accountLogs', array(), $request_params, 'post' );

        if ( $request_res['code'] != 200 ) {
            return ['code'=>$request_res['code'],'message'=>$request_res['message']];
        }

        //页码
        $accountLogs_data = [
            'page'  => intval( $request_res['data']['paging']['page'] )+1,
            'pageSize'  => $request_res['data']['paging']['pageSize'],
            'pageCount'=>$request_res['data']['paging']['pageCount'],
            'count' => !empty( $request_res['data']['paging']['recordCount'] ) ? $request_res['data']['paging']['recordCount'] : 0,
        ];

        foreach ( $request_res['data']['records'] as $key=>$value ) {

            $accountLogs_data['data'][] = [
                'createTime'  => date('Y-m-d H:i:s',strtotime($value['tranTime'])), //时间
                'changeAccount' => abs( $value['occurTotal'] ), //增加或减少的金额
                'code' => $value['num'], //消费代码
                'remark' => $value['action'], //消费名称
                'storeName' => $value['store'], //店名称
                'storeCode' => $value['store'], //店号
                'oldScore' => $value['oldBalance'], //原始金额
                'changeType' => $value['action'] =='消费' ? 0 : 1 , //状态 ,1:充值金额  0: 扣除金额
            ];
        }


        return ['code'=>200,'message'=>$request_res['message'],'data'=>$accountLogs_data];

    }

}